package C036;

import java.util.Arrays;

/**
 * ClassName: C06
 * Package: C036
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/21 11:05
 * @Version 1.0
 * @Since 1.0
 */
public class C06 {
    // 不提交这个类
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode3.right = treeNode5;
        System.out.println((serialize(treeNode1)));
        TreeNode deserialize = deserialize(serialize(treeNode1));
        System.out.println(serialize(deserialize));
    }

    // 序列化
    public static String serialize(TreeNode root) {
        if(root == null) {
            return "#,";
        }
        StringBuilder str = new StringBuilder();
        process(root, str);
        return str.toString();
    }

    private static void process(TreeNode root, StringBuilder str) {
        if(root == null) {
            str.append("#,");
            return;
        }
        str.append(root.val + ",");
        process(root.left, str);
        process(root.right, str);
    }

    static int cnt = 0;
    // 反序列化
    public static TreeNode deserialize(String data) {
        String[] strs = data.split(",");
        cnt = 0;
        return process2(strs);
    }

    private static TreeNode process2(String[] strs) {
        if("#".equals(strs[cnt])) {
            cnt++;
            return null;
        }
        TreeNode cur = new TreeNode(Integer.parseInt(strs[cnt++]));
        cur.left = process2(strs);
        cur.right = process2(strs);
        return cur;
    }
}
